<?php

class InternalLibStandardFunctions implements CliLibrary
{
	private static $functions = array(
		'if' => 'f_if',
		'while' => 'f_while',
	);

	public static function addLibrary (CliMode $mode)
	{
		$mode->addFunctions(__CLASS__, self::$functions);
	}

	public static function f_if (ArgContext $args)
	{
		$args->requireCount(1, 3);
		$clause = $args->toBool(0);

		switch ($args->argCount())
		{
			case 1:
				return $clause;

			case 2:
				return $clause ? $args->toValue(1) : false;

			case 3:
				return $clause ? $args->toValue(1) : $args->toValue(2);
		}
	}

	public static function f_while (ArgContext $args)
	{
		$args->requireCount(1, 2);
		$value = false;

		if ($args->argCount() == 1)
		{
			$args->requireTypes('expression');

			do
			{
				$value = $args->toBool(0);
			}
			while ($value);
		}
		else
		{
			$args->requireTypes('expression', 'expression');

			while ($args->toBool(0))
			{
				$value = $args->toValue(1);
			}
		}

		return $value;
	}
}
?>